/**
 * Created by 游永年 on 2019-01-19 11:31.
 * 多个标签选择器
 * data 如果会卡,移入constructor一次构造,一般不会,因为页面东西太少了,不用过于考虑性能问题
 */

'use strict'
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import style from './TagItems.less';

class TagItems extends Component {
  static defaultProps = {
    type: 'one',
  }

  render() {
    const {data = [], children = ""} = this.props;

    return (
      <div className={style.tagContainer}>
        <div className={`${style.label} am-input-label am-input-label-5`}>
          {children}
      </div>
        <div className={style.input}>
          {data.map(({name, value}) => {
            const c=this.checkSelect(value);
            return <div
              className={`${style.tag} ${c?style.tagSelected:null}`}
              key={value + ''}
              onClick={_ => this.onChange(value,!c)}
            >
              {name}
            </div>
          })}
        </div>
      </div>
    );
  }

  checkSelect=val=>{
    const {value, type}=this.props;
    if (type === 'one') {
      return value === val;
    } else if (type === 'multi') {
        if (!!value) {
          return new Set(value).has(val);
        } else {
          return false;
        }
      }
    }

  onSearch = (val) => {
    this.props.dispatch({type: 'home/search', val});
  }

  onChange = (newVal, checked = false) => {
    const {onChange, type, value = []} = this.props;
    if (type === 'one') {
      onChange(newVal);
    } else if (type === 'multi') {
      if (checked) {
        onChange([...value, newVal]);
      } else {
        const set=new Set(value);
        set.delete(newVal);
        onChange(Array.from(set));
      }
    }
  }
}

TagItems.propTypes = {
  onChange: PropTypes.func,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  type: PropTypes.oneOf(['one', 'multi']),//单选还是多选
  data: PropTypes.array,//数据项[{name,value}]
};

export default TagItems;

